package esi.t2no1.dao.loadprofile;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;
import static esi.t2no1.util.DaoUtil.extractFirst;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;

import esi.t2no1.ws.model.LoadProfile;

/**
 * 
 * @author Reimo Rebane
 * 
 */
public class LoadProfileDAOImpl implements LoadProfileDAO {

	private SimpleJdbcTemplate simpleJdbcTemplate;
	private SimpleJdbcInsert createLoadProfile;

	private static RowMapper<LoadProfile> loadProfileMapper = new RowMapper<LoadProfile>() {

		@Override
		public LoadProfile mapRow(ResultSet rs, int rowNum) throws SQLException {
			LoadProfile lp = new LoadProfile();
			lp.setSupplierId(rs.getString("supplierId"));
			lp.setCalculationAreaId(rs.getString("calculationAreaId"));
			lp.setTotalAreaInput(rs.getLong("totalAreaInput"));
			lp.setProfileSettledConsumption(rs
					.getLong("profileSettledConsumption"));
			lp.setNetworkLossConsumption(rs.getLong("networkLossConsumption"));
			lp.setProfileStartDate(rs.getDate("profileStartDate"));
			lp.setProfileEndDate(rs.getDate("profileEndDate"));
			return lp;
		}
	};

	@Override
	public Long createLoadProfile(LoadProfile loadProfile) {
		return createLoadProfile.executeAndReturnKey(
				new BeanPropertySqlParameterSource(loadProfile)).longValue();
	}

	@Override
	public List<LoadProfile> getSupplierLoadProfiles(String supplierId) {
		String sql = "select * from loadprofile where supplierId = ? order by profileStartDate";
		return simpleJdbcTemplate.query(sql, loadProfileMapper, supplierId);
	}

	@Autowired
	public void setDataSource(DataSource dataSource) {
		simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
		createLoadProfile = new SimpleJdbcInsert(dataSource)
				.withTableName("loadprofile").usingGeneratedKeyColumns("id");
	}

	@Override
	public LoadProfile getLatestLoadProfile(String supplierId) {
		String sql = "select * from loadprofile where supplierId = ? order by profileStartDate desc limit 0, 1";
		return extractFirst(simpleJdbcTemplate.query(sql, loadProfileMapper,
				supplierId));
	}
}
